<template>
  <div class="app-container">
    <div class="btns">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
    <div class="content-container">
      <el-divider content-position="left">基础信息</el-divider>
      <div class="item1">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="公司名称" prop="companyName">
            <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
          </el-form-item>
          <el-form-item label="公司星级" prop="companyLevel">
            <el-rate v-model="form.companyLevel" style="position: relative;top: 6px"></el-rate>
          </el-form-item>
<!--          <el-form-item label="人才数量" prop="talentAmount">
            <el-input v-model="form.talentAmount" placeholder="请输入人才数量"/>
          </el-form-item>-->
          <el-form-item label="市场区域" prop="marketArea">
            <el-input v-model="form.marketArea" placeholder="请输入市场区域"/>
          </el-form-item>
          <el-form-item label="联系人" prop="companyPrincipal">
            <el-input v-model="form.companyPrincipal" placeholder="请输入联系人"/>
          </el-form-item>
          <el-form-item label="联系方式" prop="companyPhone">
            <el-input v-model="form.companyPhone" placeholder="请输入联系方式"/>
          </el-form-item>
          <el-form-item label="终端产品" prop="companyPhone" v-if="queryParams.categoryParentId == 1">
            <el-input v-model="form.companyProducts" placeholder="请输入终端产品"/>
          </el-form-item>
          <el-form-item label="供应量" v-if="queryParams.categoryParentId == 1" prop="designCapacity">
            <el-input v-model="form.designCapacity" placeholder="请输入供应量"/>
          </el-form-item>
          <el-form-item label="设计产能" v-if="queryParams.categoryParentId == 1" prop="designCapacity">
            <el-input v-model="form.designCapacity" placeholder="请输入设计产能"/>
          </el-form-item>
          <el-form-item label="公司地址" prop="companyAddress">
            <el-input v-model="form.companyAddress" placeholder="请输入公司地址"/>
          </el-form-item>
          <el-form-item label="工厂类别" prop="categoryId">
            <treeselect v-model="form.categoryId" style="width: 176px;" :disable-branch-nodes="true"
                        :options="categoryOptions"
                        placeholder="请选择工厂类别"
            />
          </el-form-item>
        </el-form>
      </div>

      <div class="item2">
        <div class="left">
          <div class="from-box">
            <el-divider content-position="left">详情信息</el-divider>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="公司简介" prop="companyProfile">
                <el-input type="textarea" autosize v-model="form.companyProfile" placeholder="请输入公司简介"></el-input>
              </el-form-item>
              <el-form-item label="公司地址经度" prop="longitude">
                <el-input v-model="form.longitude" disabled/>
              </el-form-item>
              <el-form-item label="公司地址纬度" prop="longitude">
                <el-input v-model="form.latitude" disabled/>
                <el-button type="primary" size="mini" @click="handleChoicePosition">选择公司经纬度</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="right">
          <div class="from-box">
            <el-divider content-position="left">资料上传</el-divider>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="720云链接" prop="cloudLink">
                <el-input v-model="form.cloudLink"/>
                <span slot="label">
                  <el-tooltip content="输入的链接以`http(s)://`开头" placement="top">
                  <i class="el-icon-question"></i>
                  </el-tooltip>
                  720云链接
                </span>
              </el-form-item>
              <el-form-item label="模型文件" prop="fileModal">
                <fileUpload ref="fileUpload"
                            :uploadFiles="uploadFiles"
                            :handleUploadFile="handleUploadFile" :value="fileModal"></fileUpload>
              </el-form-item>
              <el-form-item label="描述大图" prop="fileImage">
                <img-upload ref="uploadImage1" :value="fileImage" :limit="1" :isDetails="true"
                            :handleUploadImage="handleUploadImage" :uploadFiles="uploadFiles"
                ></img-upload>
              </el-form-item>
              <el-form-item label="公司详细轮播图" prop="fileImageList">
                <img-upload ref="uploadImage2" :value="fileImageList" :limit="10" :isDetails="true"
                            :isList="true" :handleUploadImageList="handleUploadImageList" :uploadFiles="uploadFiles"
                ></img-upload>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>


    <el-dialog
      :title="importUpload.title"
      :visible.sync="importUpload.open"
      append-to-body
      width="400px"
    >
      <el-upload
        ref="upload"
        :action="importUpload.url"
        :auto-upload="false"
        :disabled="importUpload.isUploading"
        :headers="importUpload.headers"
        :limit="1"
        :on-progress="handleImportFileUploadProgress"
        :on-success="handleImportFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-button size="mini" type="primary" @click="importTemplate">
            下载模板<i class="el-icon-download el-icon--right"></i>
          </el-button>
          <div style="color: red; display: inline">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="importUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--显示经纬度-->
    <el-dialog title="经纬度选择" :visible.sync="openPosition" width="80%" append-to-body>
      <div class="mapBox" style="width: 100%;height: 70vh">
        <div class="left">
          <Map1 v-if="openPosition" style="width: 100%;height: 100%" @showPosition="showPosition" ref="childMap"></Map1>
        </div>
        <div class="right">
          <el-form ref="form2" :model="form2" :rules="rules2" label-width="120px">
            <el-form-item label="定位名称" prop="positionName">
              <el-input v-model="form2.positionName" placeholder="请输入定位名称"/>
              <el-button type="primary" size="mini" @click="handleSelectPosition">确定</el-button>
            </el-form-item>
            <el-form-item label="当前选择经度" prop="longitude">
              <el-input v-model="form2.longitude" disabled/>
            </el-form-item>
            <el-form-item label="当前选择纬度" prop="latitude">
              <el-input v-model="form2.latitude" disabled/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMarks, getMarks, delMarks, addMarks, updateMarks } from '@/api/system/marks'
import imgUpload from '@/components/ImageUpload/index.vue'
import fileUpload from '@/components/FileUpload'
import Map1 from '@/components/Map1'
import { getToken } from '@/utils/auth'
import { getCityCode } from '@/utils/utils'
import { getTreeSelect, listCategory } from '@/api/system/category'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

let vm = {}
export default {
  name: 'index',
  components: {
    Map1,
    Treeselect,
    imgUpload,
    fileUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业管理表格数据
      marksList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        companyProfile: null,
        companyLevel: null,
        longitude: null,
        latitude: null,
        categoryId: null,
        categoryParentId: 7
      },
      // 表单参数
      form: {},
      //当前类别id
      parentId: 1,
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: '公司名称不能为空', trigger: 'blur' }
        ],
        companyLevel: [
          { required: true, message: '公司星级不能为空', trigger: 'blur' }
        ],
        companyProfile: [
          { required: true, message: '公司简介不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '工厂类别不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '坐标经度不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '坐标纬度不能为空', trigger: 'blur' }
        ]
      },
      rules2: {
        longitude: [
          { required: true, message: '坐标经度不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '坐标纬度不能为空', trigger: 'blur' }
        ]
      },
      importUpload: {
        // 是否显示弹出层（班级导入）
        open: false,
        // 弹出层标题（班级导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/marks/importData'
      },
      //显示经纬度
      openPosition: false,
      form2: {
        //定位名称
        positionName: null,
        longitude: null,
        latitude: null
      },
      //工厂类别 -- 格式化
      categoryOptions: [],
      //工厂类别 -- 未格式化
      categoryOptions2: [],
      //当前id
      marksId: null,
      //显示上传弹出框
      dialogFileUpload: false,
      //大图
      fileImage: '',
      //图片列表
      fileImageList: [],
      //模型
      fileModal:'',
      isPushFileList: false,
      isFileImage: false,
      isFileModal:false,
    }
  },

  created() {
    this.marksId = this.$route.query.marksId
    this.queryParams.categoryParentId = this.$route.query.categoryParentId
    this.handleUpdate()
    //获取格式化后的类别
    getTreeSelect().then(res => {
      this.categoryOptions = []
      this.categoryOptions = res.data.filter(item => item.id == this.queryParams.categoryParentId)
      this.categoryOptions = this.categoryOptions[0].children
      console.log(this.categoryOptions, 'this.categoryOptions')
    })
    // 获取未格式化类别
    listCategory().then(res => {
      this.categoryOptions2 = []
      this.categoryOptions2 = res.data
    })
  },
  computed: {},
  filters: {
    formatCategory: function(id, categoryOptions2) {
      const a = categoryOptions2.filter(item => {
        return id == item.categoryId
      })
      return a[0].categoryName
    }
  },
  methods: {
    handleUploadFile(){
      console.log("改变了Modal")
      this.isFileModal = true
    },
    handleUploadImage() {
      this.isFileImage = true
      console.log("改变了Banner")
    },
    handleUploadImageList() {
      this.isPushFileList = true
      console.log('改变了列表')
    },
    //返回上一级
    handleBack() {
      this.$router.go(-1)
    },
    // 文件上传中处理
    handleImportFileUploadProgress(event, file, fileList) {
      this.$refs.upload.isUploading = true
    },
    // 文件上传成功处理
    handleImportFileSuccess(response, file, fileList) {
      this.importUpload.open = false
      this.importUpload.isUploading = false
      this.$refs.upload.clearFiles()
      this.loading_const.close()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()

    },
    importTemplate() {
      const fileName = '现代建筑产业信息表制造业.xlsx'
      this.download('system/marks/importTemplate', {
        fileName
      }, fileName)
    },
    openLoading() {
      this.loading_const = this.$loading({
        lock: true,
        text: '导入时间较长,请耐心等待。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'loading_area'
      })
    },
    // 提交上传文件
    submitFileForm() {
      this.openLoading()
      this.$refs.upload.submit()
    },
    //导入企业
    handleImport() {
      this.importUpload.title = '企业批量导入'
      this.importUpload.open = true
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮 -- 经纬度
    cancel2() {
      this.openPosition = false
      this.form2 = {
        positionName: null,
        longitude: null,
        latitude: null
      }
      this.resetForm('form2')
    },
    // 表单重置
    reset() {
      this.form = {
        marksId: null,
        companyName: null,
        companyProfile: null,
        companyLevel: null,
        longitude: null,
        latitude: null,
        categoryId: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.marksId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 转换企业类别数据结构 */
    normalizer(node) {
      console.log(node, 'node')
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加企业管理'
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset()
      getMarks(this.marksId).then(response => {
        this.form = response.data
        this.fileImageList = response.data.bannerFile
        this.fileImage = response.data.imageFile
        console.log(this.fileImage,"fileImage")
        this.fileModal = response.data.modelFile
        console.log(this.form, 'this.form')
        console.log(this.fileImageList, 'this.fileImageList')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(  valid => {
        if (valid) {
          //轮播图列表
          if (this.isPushFileList) {
            //大图
            this.$refs.uploadImage2.uploadData.fileType = 4
            this.$refs.uploadImage2.uploadData.marksId = this.marksId
            this.$refs.uploadImage2.handleSubmit()
          }

          if (this.isFileImage) {
            this.$refs.uploadImage1.uploadData.fileType = 3
            this.$refs.uploadImage1.uploadData.marksId = this.marksId
            this.$refs.uploadImage1.handleSubmit()
          }

          if(this.isFileModal){
            this.$refs.fileUpload.uploadData.fileType = 2
            this.$refs.fileUpload.uploadData.marksId = this.marksId
            this.$refs.fileUpload.handleSubmit()
          }
          if(!this.isPushFileList && !this.isFileModal && !this.isFileImage){
            this.uploadFiles()
          }
        }
      })
    },
    //上传文件
    uploadFiles(){
      console.log("自组建触发")
      updateMarks(this.form).then(res => {
        this.$modal.msgSuccess('修改成功')
        this.handleUpdate(this.marksId)
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const marksIds = row.marksId || this.ids
      this.$modal.confirm('是否确认删除企业管理编号为"' + marksIds + '"的数据项？').then(function() {
        return delMarks(marksIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/marks/export', {
        ...this.queryParams
      }, `marks_${new Date().getTime()}.xlsx`)
    },
    /** 选择经纬度*/
    handleChoicePosition() {
      this.openPosition = true
      this.form2.longitude = this.form.longitude
      this.form2.latitude = this.form.latitude
      console.log(this.form2, 'this.form2')
      //获取经纬度转换为的cityCode
      if (this.form2.longitude && this.form2.latitude) {
        getCityCode(this.form2.longitude, this.form2.latitude).then(response => {
          this.form2.positionName = response.regeocode.formatted_address
          this.$nextTick(()=>{
            setTimeout(()=>{
              this.handleSelectPosition()
            },500)
          })
        })
      }
    },
    //地图查询定位
    handleSelectPosition() {
      this.$refs.childMap.searchPosition(this.form2.positionName)
    },
    //显示经纬度
    showPosition(x, y, code) {
      this.form2.longitude = x
      this.form2.latitude = y
      this.form.cityCode = code
    },
    //确认选择经纬度
    submitForm2() {
      this.$refs['form2'].validate(valid => {
          if (valid) {
            this.form.longitude = this.form2.longitude
            this.form.latitude = this.form2.latitude
            this.openPosition = false
          }
        }
      )
    }
  }
}
</script>
<style scoped lang="scss">
.mapBox {
  display: flex;

  .left {
    flex: 2;
    height: 70vh;
    border: 2px solid #ccc;
  }

  .right {
    flex: 1;
    margin-left: 20px;
    height: 70vh;
  }
}

.app-container {
  .content-container {
    .item1 {
      .el-form {
        display: flex;
        flex-wrap: wrap;
      }

      .el-form-item {
        width: 24%;
      }
    }

    .item2 {
      display: flex;

      .left {
        flex: 1;

        .from-box {
          width: 80%;
        }
      }

      .right {
        flex: 1;

        .from-box {
          margin: 0 auto;
          width: 80%;
        }
      }
    }

  }
}

.btns {
  display: flex;
  justify-content: right;
  margin-right: 20px;
}
</style>


